package com.amarsoft.apot.global;

import com.alibaba.fastjson.JSONArray;
import com.amarsoft.apot.enums.ResultCodeEnum;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description: 全局异常处理器----> 全局捕获异常和自定义全局捕获异常
 * @title: WeaverControllerAdvice
 * @Author szh
 * @Date: 2021/12/27 15:13
 */

//ControllerAdvice 的增强版，包含了@ControllerAdvice 和 @ResponseBody 注解功能；
// 默认处理所有 controller 中被 @RequestMapping注解的方法
@RestControllerAdvice
public class WeaverControllerAdvice {

    @ResponseBody
    @ExceptionHandler(value = {Exception.class,RuntimeException.class})
    public String exceptionHandler(Exception ex) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", ResultCodeEnum.FAILURE.getCode());
        // 但是assert的异常属于IllegalArgumentException 直接  throw new IllegalArgumentException(message);
        if (null != ex.getCause()){
            map.put("msg", ex.getCause().getMessage());
        }else {
            map.put("msg", ex.getMessage());
        }

        JSONArray jArray = new JSONArray();
        jArray.add(map);
        return jArray.toString();
    }

}